package jp.co.sharp.android.parents.kidsguard.activity.edit;

import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.bluetooth.parentble.ParentBleTransfer;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import jp.co.sharp.android.parents.kidsguard.App;
import jp.co.sharp.android.parents.kidsguard.R;
import jp.co.sharp.android.parents.kidsguard.activity.edit.adapter.ContactListAdapter;
import jp.co.sharp.android.parents.kidsguard.activity.home.HomeActivity;
import jp.co.sharp.android.parents.kidsguard.activity.setting.ContactOptActivity;
import jp.co.sharp.android.parents.kidsguard.activity.setting.SettingActivity;
import jp.co.sharp.android.parents.kidsguard.common.DealWithWaitingDlg;
import jp.co.sharp.android.parents.kidsguard.common.DelDeviceConfirmDlg;
import jp.co.sharp.android.parents.kidsguard.common.ProcessWarningDlg;
import jp.co.sharp.android.parents.kidsguard.contants.Constants;
import jp.co.sharp.android.parents.kidsguard.contants.PageSerialNumConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestMethodConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestReceiverConstants;
import jp.co.sharp.android.parents.kidsguard.dto.BluetoothReceiverDto;
import jp.co.sharp.android.parents.kidsguard.dto.ContactListDto;
import jp.co.sharp.android.parents.kidsguard.entity.KidInfoEntity;
import jp.co.sharp.android.parents.kidsguard.thread.BusinessThread;

public class ContactsActivity extends AppCompatActivity {

    private App mApp;

    private final static int CONTACT_ADD_CODE = 1000;

    public ParentBleTransfer mParentBleTransfer;

    private ListView mListView;

    private Boolean mOnSyncResultFlag = false;

    private Boolean mGetContactsFlag = false;

    private DealWithWaitingDlg mDealWithWaitingDlg;

    private KidInfoEntity mKidInfoEntity;

    private boolean mScreenOperate = false;

    private boolean mUnReceiver = true;

    private static final String TAG = "TAG";
    // ページジャンプ
    private boolean mPageJumpFlag = false;
    // システムホームプレス
    private boolean mSystemHomeFlag = false;
    // プログラムロック
    private String mSyncLock = "syncLock";
    // 編集を再開しています...
    private boolean mEditReopening = false;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        Log.i(TAG, "ContactsActivity_onActivityResult");
        super.onActivityResult(requestCode, resultCode, intent);
        initReceiver();
        // Dlg
        String message = "キッズケータイから情報を取得しています...";
        mDealWithWaitingDlg = new DealWithWaitingDlg(ContactsActivity.this, R.style.commonDlg, message, true);
        mDealWithWaitingDlg.show();
        sendGetContactsToKid();
    }

    @Override
    public void onBackPressed() {
        sendExitToKid();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.i(TAG, "ContactsActivity_onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contacts);
        mListView = (ListView)findViewById(R.id.contactList);
        mApp = (App)getApplication();
        initListener();
        initReceiver();
        init();
    }
    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG, "ContactsActivity_onStart");
        mApp.setAppStatus(Constants.APP_STATUS_INIT);
    }


    private void initListener() {
        Log.i(TAG, "ContactsActivity_initListener");
        ImageView back = findViewById(R.id.backImage);
        ImageView addContactsImage = findViewById(R.id.addContactsImage);
        mKidInfoEntity = ((App) getApplication()).findKidInfoBySelect();
        TextView mKidNameTv = findViewById(R.id.textViewKidName);
        String kidNameDescribe = mKidInfoEntity.getKidName()+"のキッズケータイ";
        mKidNameTv.setText(kidNameDescribe);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sendExitToKid();
            }
        });
        addContactsImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPageJumpFlag = true;
                    Intent intent = new Intent();
                    intent.setClass(ContactsActivity.this, ContactAddActivity.class);
                    intent.putExtra("MODE", "ADD");
                    startActivityForResult(intent,CONTACT_ADD_CODE);
            }
        });
    }

    private void init() {
        Log.i(TAG, "ContactsActivity_init");
        String message = "キッズケータイから情報を取得しています...";
        mDealWithWaitingDlg = new DealWithWaitingDlg(ContactsActivity.this, R.style.commonDlg, message, true);
        mDealWithWaitingDlg.show();
        sendIsUsingToKid();

    }
    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i(TAG, "ContactsActivity_onRestart");
        synchronized (mSyncLock) {
            if (mSystemHomeFlag) {
                if ((mApp.getAppStatus() != Constants.APP_STATUS_USER_PRESENT)&&(!mEditReopening)) {
                    String message = "編集を再開しています...";
                    mDealWithWaitingDlg = new DealWithWaitingDlg(ContactsActivity.this, R.style.commonDlg, message, false);
                    mDealWithWaitingDlg.show();
                    mScreenOperate = true;
                    mEditReopening = true;
                    sendIsUsingToKid();
                    // ブロードキャストの再登録
                    unregisterReceiver(systemReceiver);
                    initReceiver();
                }
                mSystemHomeFlag = false;
            }
        }
    }
    @Override
    protected void onStop() {
        super.onStop();
        Log.i(TAG, "ContactsActivity_onStop");
        if (!mUnReceiver) {
            synchronized (mSyncLock) {
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(receiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
                mUnReceiver = true;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "ContactsActivity_onDestroy");
        if (!mUnReceiver) {
            synchronized (mSyncLock) {
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(receiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
                mUnReceiver = true;
            }
        }
    }

    private void initReceiver() {
        Log.i(TAG, "ContactsActivity_initReceiver");
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_USER_PRESENT);
        // ホームボタン
        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        // Bluetooth
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED);
        //isFinish
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED);
        registerReceiver(receiver, filter);
        registerReceiver(systemReceiver, filter);
        this.mParentBleTransfer = ((App) getApplication()).getmParentBleTransfer();
        mUnReceiver = false;
    }

    /**
     * システム放送
     */
    private final BroadcastReceiver systemReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getAction();
                if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                    Log.i(TAG, "ContactsActivity_systemReceiver_ACTION_SCREEN_OFF");
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_SCREEN_OFF);
                        mScreenOperate = true;
                        sendExitToKid();
                    }
                } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
                    Log.i(TAG, "ContactsActivity_systemReceiver_ACTION_USER_PRESENT");
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_USER_PRESENT);
                        if (!mPageJumpFlag) {
                            String message = "編集を再開しています...";
                            mDealWithWaitingDlg = new DealWithWaitingDlg(ContactsActivity.this, R.style.commonDlg, message, false);
                            mDealWithWaitingDlg.show();
                            mScreenOperate = true;
                            mEditReopening = true;
                            sendIsUsingToKid();
                            // ブロードキャストの再登録
                            unregisterReceiver(systemReceiver);
                            initReceiver();
                        }
                    }
                } else if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
                    Log.i(TAG, "ContactsActivity_systemReceiver_ACTION_CLOSE_SYSTEM_DIALOGS");
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_CLOSE_SYSTEM_DIALOGS);
                        mSystemHomeFlag = true;
                        mScreenOperate = true;
                        sendExitToKid();
                    }
                } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED.equals(action)) {
                    Log.i(TAG, "ContactsActivity_receiver_RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED");
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    String macAddress = bluetoothReceiverDto.getAddress();
                    if (((App)getApplication()).isMimamoriCheck(macAddress)) {
                        ((App)getApplication()).addmLsIsMimamori(macAddress);
                        sendExitToKid();
                        mPageJumpFlag = true;
                        Intent intent1 = new Intent();
                        intent1.setAction(Constants.ACTION_IS_MIMAMORI);
                        intent1.setClass(ContactsActivity.this, HomeActivity.class);
                        startActivity(intent1);
                    } else {
                        mKidInfoEntity.setBtConnStatus(Constants.DEVICE_DISCONNECTION_SUCCESS);
                        ((App)getApplication()).updateKidInfo(mKidInfoEntity);

                        String message = mKidInfoEntity.getKidName() + "と切断されました。編集を中断します。";
                        ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(ContactsActivity.this, R.style.commonDlg, message);
                        processWarringDlg.show();
                        processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                            @Override
                            public void onOperateSet() {
                                processWarringDlg.dismiss();
                                mPageJumpFlag = true;
                                Intent intent1 = new Intent();
                                intent1.setClass(ContactsActivity.this, SettingActivity.class);
                                startActivity(intent1);
                            }
                        });
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
        }
    };

    /**
     * BroadcastReceiver
     */
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED.equals(action)) {
                Log.i(TAG, "ContactsActivity_receiver_RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED");
                BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                try {
                    JSONObject resp = new JSONObject(bluetoothReceiverDto.getRetStr());
                    String method = resp.getString("method");
                    if (null != method) {
                        if (RequestMethodConstants.METHOD_GET_CONTACTS.equals(method)) {
                            JSONArray data = resp.getJSONArray("data");
                            Log.i(TAG, "ContactsActivity_receiver_RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED_getContacts_:"+data.toString());
                            List<ContactListDto> list = new ArrayList<>();
                            for (int i =0;i<data.length();i++){
                                ContactListDto contactListDto = new ContactListDto();
                                contactListDto.setId(data.getJSONObject(i).getInt("id"));
                                contactListDto.setName(data.getJSONObject(i).getString("name"));
                                contactListDto.setPhone(data.getJSONObject(i).getString("phone"));
                                contactListDto.setYomi(data.getJSONObject(i).getString("yomi"));
                                contactListDto.setPortrait(data.getJSONObject(i).getString("portrait"));
                                list.add(contactListDto);
                            }
                            mListView.setAdapter(new ContactListAdapter(ContactsActivity.this,R.layout.contact_list_item,list,
                                    new ContactListAdapter.OnClickItemListenter(){
                                        @Override
                                        public void chooseItemClick(int position, View view) {
                                            mPageJumpFlag = true;
                                            Intent intent = new Intent();
                                            intent.setClass(ContactsActivity.this, ContactAddActivity.class);
                                            intent.putExtra("MODE", "EDIT");
                                            intent.putExtra("INFO",list.get(position));
                                            startActivityForResult(intent,CONTACT_ADD_CODE);
                                        }
                                    }));
                            handler.sendEmptyMessage(0);
                        } else if (RequestMethodConstants.METHOD_GET_OPERATING_STATE.equals(method)) {
                            JSONObject data = resp.getJSONObject("data");
                            Log.i(TAG, "ContactsActivity_receiver_RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED_getOperatingState_:"+data.toString());
                            if (Constants.IS_USING_OK.equals(data.getString("state"))) {
                                //发送enter
                                sendEnterToKid();
                            }else {
                                handler.sendEmptyMessage(0);
                                String message = "別のスマートフォンから操作中のため、設定を変更できません。";
                                ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(ContactsActivity.this, R.style.commonDlg, message);
                                processWarringDlg.show();
                                processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                                    @Override
                                    public void onOperateSet() {
                                        processWarringDlg.dismiss();
                                        // ページジャンプ
                                        mPageJumpFlag = true;
                                        ContactsActivity.this.finish();
                                    }
                                });
                            }
                        } else if (RequestMethodConstants.METHOD_ON_SYNC_RESULT.equals(method)) {
//                            if (Constants.ON_SYNC_RESULT.equals(resp.getString("result"))) {
//
//                            }
                        } else if (RequestMethodConstants.METHOD_ON_OPERATE_INTERRUPT.equals(method)){
                            Log.i(TAG, "ContactsActivity_receiver_RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED_onOperateInterrupt");
                            String message = "キッズケータイが操作されました。編集を中断します。";
                            ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(ContactsActivity.this, R.style.commonDlg, message);
                            processWarringDlg.show();
                            processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                                @Override
                                public void onOperateSet() {
                                    processWarringDlg.dismiss();
                                    back();
                                }
                            });
                        }
                    }
                } catch (JSONException e) {
                     Log.e(TAG,e.getMessage());
                }

            } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED.equals(action)) {
                Log.i(TAG, "ContactsActivity_receiver_RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED");
                //isFinish
                BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                if (bluetoothReceiverDto.isFinished()) {
                    if (mGetContactsFlag) {
                        //发送 getProfile 请求=                                                                                                                 b
                        mGetContactsFlag = false;
                        if (!mScreenOperate){
                            sendGetContactsToKid();
                        }else {
                            mScreenOperate = false;
                            mEditReopening = false;
                            handler.sendEmptyMessage(0);
                        }
                    }
                    if (mOnSyncResultFlag) {
                        mOnSyncResultFlag = false;
                        if (!mScreenOperate){
                            back();
                        }
                    }
                }

            }
        }
    };
    public void  sendGetContactsToKid(){
        Log.i(TAG, "ContactsActivity_sendGetContactsToKid");
        try{
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("method","getContacts");
            jsonObject.put("data",JSONObject.NULL);
            new BusinessThread(Constants.SEND_KID_GET_INFO,
                    mParentBleTransfer,
                    mKidInfoEntity,
                    jsonObject,
                    PageSerialNumConstants.PAGE_SERIAL_CONTACT).start();
        }catch (JSONException e){
             Log.e(TAG,e.getMessage());
        }catch (Exception e){
             Log.e(TAG,e.getMessage());
        }
    }
    public void sendExitToKid(){
        Log.i(TAG, "ContactsActivity_sendExitToKid");
        mOnSyncResultFlag = true;
        new BusinessThread(Constants.SEND_KID_EXIT,
                mParentBleTransfer,
                mKidInfoEntity,
                null,
                PageSerialNumConstants.PAGE_SERIAL_CONTACT).start();
    }

    /**
     *  is using
     */
    public void sendIsUsingToKid()  {
        Log.i(TAG, "ContactsActivity_sendIsUsingToKid");
        try{
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("method","getOperatingState");
            jsonObject.put("data",JSONObject.NULL);
            new BusinessThread(Constants.SEND_KID_IS_USING,
                    mParentBleTransfer,
                    mKidInfoEntity,
                    jsonObject,
                    PageSerialNumConstants.PAGE_SERIAL_CONTACT).start();
        }catch (JSONException e){
             Log.e(TAG,e.getMessage());
        }catch (Exception e){
             Log.e(TAG,e.getMessage());
        }
    }


    private void back() {
        Log.i(TAG, "ContactsActivity_back");
        mPageJumpFlag = true;
        Intent intent = new Intent();
        intent.setClass(this, EditActivity.class);
        startActivity(intent);
    }

    /**
     * enter
     */
    public void sendEnterToKid(){
        Log.i(TAG, "ContactsActivity_sendEnterToKid");
        mGetContactsFlag = true;
        new BusinessThread(Constants.SEND_KID_ENTER,
                mParentBleTransfer,
                mKidInfoEntity,
                null,
                PageSerialNumConstants.PAGE_SERIAL_CONTACT).start();
    }



    /**
     * Dialog閉じる
     */
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (null != mDealWithWaitingDlg && mDealWithWaitingDlg.isShowing()) {
                mDealWithWaitingDlg.dismiss();
            }
        }
    };
}
